const fsExtra = require("fs-extra");
const path = require("path");
const router = require("koa-router")();
const UPLOAD_DIR = path.resolve(__dirname, "..", "files");

router.get("/", async (ctx) => {
  ctx.body = { code: 200, result: "get /check is connect!!!" };
});

router.post("/file", async (ctx) => {
  // 切片得从files字段获取，不在body中 基于 koa-body插件
  const file = ctx.request.files.chunk;
  // 获取文件Hash和切片序号
  const body = ctx.request.body;
  const fileHash = body.fileHash;
  const chunkHash = body.chunkHash;
  const chunkDir = `${UPLOAD_DIR}/${fileHash}`;
  const chunkIndex = chunkHash.split("-")[1];
  const chunkPath = `${UPLOAD_DIR}/${fileHash}/${chunkIndex}`;

  // 不存在目录，则新建目录
  if (!fsExtra.existsSync(chunkDir)) {
    await fsExtra.mkdirs(chunkDir);
  }

  // 这里的file.path为上传切片的临时地址
  await fsExtra.move(
    file.path,
    path.resolve(chunkDir, chunkHash.split("-")[1])
  );

  ctx.body = { code: 200, result: "接收成功" };
});

router.get("/mergeFile", async (ctx) => {
  const { fileName, fileHash, chunkSize } = ctx.request.query;
  const chunkDir = path.resolve(UPLOAD_DIR, fileHash);
  // console.log("params", fileName, fileHash, chunkSize);
  // 读取文件夹下所有的分片
  const chunkPaths = await fsExtra.readdir(chunkDir);
  const chunkNumber = chunkPaths.length;
  let count = 0;
  // 切片排序 防止乱序
  chunkPaths.sort((a, b) => a - b);
  chunkPaths.forEach((chunk, index) => {
    const chunkPath = path.resolve(UPLOAD_DIR, fileHash, chunk);
    // 创建可写流
    const writeStream = fsExtra.createWriteStream(fileHash + fileName, {
      start: index * chunkSize,
      end: (index + 1) * chunkSize,
    });
    // 创建可读流
    const readStream = fsExtra.createReadStream(chunkPath);
    readStream.on("end", () => {
      // 删除切片文件
      fsExtra.unlinkSync(chunkPath);
      count++;
      // 删除切片文件夹
      if (count === chunkNumber) {
        fsExtra.rmdirSync(chunkDir);
        let uploadedFilePath = path.resolve(
          __dirname,
          "..",
          fileHash + fileName
        );
        fsExtra.move(uploadedFilePath, UPLOAD_DIR + "/" + fileHash + fileName);
      }
    });
    readStream.pipe(writeStream);
  });
  ctx.body = { code: 200, result: "接收成功" };
});

module.exports = router.routes();
